<template>
  <div class="app-container">
    <div style="display: flex;">
      <div  style="width: 300px;display: flex;flex-direction: column">
        <group-select @getGroupData="getGroupData" @reloadData="resetQuery"></group-select>
      </div>

      <div style="width: 60vw">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <!--      <el-form-item label="平台" prop="platform">-->
          <!--        <el-input-->
          <!--          v-model="queryParams.platform"-->
          <!--          placeholder="请输入平台"-->
          <!--          clearable-->
          <!--          @keyup.enter.native="handleQuery"-->
          <!--        />-->
          <!--      </el-form-item>-->
          <el-form-item label="账号昵称" prop="nickname">
            <el-input
              v-model="queryParams.nickname"
              placeholder="请输入账号昵称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="multiple"
              @click="handleUpdate"
            >批量编辑</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="multiple"
              v-hasPermi="['media:mediaAccount:add']"
              @click="setLowerUser"
            >分配账号</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              v-hasPermi="['media:mediaAccount:add']"
              @click="updateSpecial"
            >修改特效视频</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['media:mediaAccount:remove']"
            >删除</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          <div style="font-size: 13px;color: #6286e8;float: right;margin-top: 10px;margin-right: 15px">
            <!--        <a @click="copyLink('https://zhijian6.cn')">-->
            <!--          复制网页链接-->
            <!--        </a>-->
            <a href="https://toolmp.oss-cn-shenzhen.aliyuncs.com/upload/test/MediaLogin3.0.2_1684478507335.rar">
              下载登录插件</a>
          </div>
        </el-row>

        <el-table v-loading="loading" :data="accountList" height="70vh"   @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="账号头像" align="center" prop="headImgUrl" >
            <template slot-scope="scope">
              <img :src="scope.row.headImgUrl" style="width: 50px;height: 50px;border-radius: 50px">
            </template>
          </el-table-column>
          <el-table-column label="账号昵称" align="center" prop="nickname" >
            <template slot-scope="scope">
              <span style="font-size: 13px;color: #646464;">{{scope.row.nickname}}</span>
            </template>
          </el-table-column>
          <el-table-column label="绑定下级用户" align="center" prop="lowerUsername" >
            <template slot-scope="scope">
              <el-tag v-if="scope.row.lowerUsername">
                {{scope.row.lowerUsername}}
              </el-tag>
              <span v-else style="font-size: 13px;color: #9d9d9d">未绑定</span>
            </template>
          </el-table-column>

          <el-table-column label="平台" align="center" prop="platform" >
            <template slot-scope="scope">
              <img :src="require('@/assets/media/' + scope.row.platformCode + '.png' )" style="width: 30px;height: 30px;border-radius: 50px">
            </template>
          </el-table-column>
          <!--      <el-table-column label="平台图标" align="center" prop="logo" /> -->
          <el-table-column label="账号登录状态" align="center" prop="loginStatus" >
            <template slot-scope="scope">
              <el-tag :type="scope.row.loginStatus === 1 ? '' : 'danger'"
                      style="cursor:pointer"
                      @click="loginWeb(scope.row)">
                {{scope.row.loginStatus === 1 ? '已登录' : '已掉线'}}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="账号分组名称" align="center" prop="groupName" >
            <template slot-scope="scope">

              <span v-if="scope.row.groupName">{{ scope.row.groupName }}</span>
              <span v-else style="font-size: 13px;color: #9f9f9f">{{ scope.row.groupName ?  scope.row.groupName : '未分组'}}</span>
            </template>
          </el-table-column>
          <!--      <el-table-column label="两小时内是否上推荐" align="center" prop="asf">-->
          <!--        <template slot-scope="scope">-->
          <!--          <el-tag type="info">否</el-tag>-->
          <!--        </template>-->
          <!--      </el-table-column>-->


          <el-table-column label="最后扫码时间" sortable align="center" prop="lastScanTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.lastScanTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" />
          <!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
          <!--        <template slot-scope="scope">-->
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-edit"-->
          <!--            @click="handleUpdate(scope.row)"-->
          <!--            v-hasPermi="['media:mediaAccount:edit']"-->
          <!--          >修改</el-button>-->
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-delete"-->
          <!--            @click="handleDelete(scope.row)"-->
          <!--            v-hasPermi="['media:mediaAccount:remove']"-->
          <!--          >删除</el-button>-->
          <!--        </template>-->
          <!--      </el-table-column>-->
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>



    </div>

    <!-- 添加或修改账号管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" style="margin-top: 30px;margin-right: 40px" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="选择分组" prop="remark">
          <el-autocomplete
            class="inline-input"
            v-model="form.groupName"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            @select="handleSelect"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



    <!-- 下级用户选择 -->
    <el-dialog title="将账号配分给下级用户" :visible.sync="lowerOpen" width="800px" append-to-body>
      <el-table
        v-loading="loadLowerUser"
        :data="lowerUserList"
        border
        ref="tableData"
        @row-click="singleElection"
      >
        <el-table-column label="点击选中账号id" width="280">
          <template slot-scope="scope">
            <el-radio class="radio" v-model="userId" :label="scope.row.userId">&nbsp;</el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="userId" label="主键" v-if="false" ></el-table-column>
        <el-table-column prop="username" label="账号名称" ></el-table-column>
        <!--      <el-table-column prop="userId" label="用户id"></el-table-column>-->
        <!--        <el-table-column label="创建时间" align="center" prop="createTime">-->
        <!--          <template #default="scope">-->
        <!--            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column prop="loginDate" label="登录时间" ></el-table-column>
        <el-table-column prop="loginIp" label="登录ip" >
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitLowerForm">确 定</el-button>
        <el-button @click="cancelLower">取 消</el-button>
      </div>
    </el-dialog>



    <!--    修改特效视频弹框 -->
    <el-dialog title="修改特效视频" :visible.sync="specialOpen" width="800px" append-to-body>
      <el-table
        v-loading="loadSpecial"
        :data="draftsList"
        ref="tableData"
        @row-click="singleElection"
      >
        <el-table-column prop="nickname"  label="账号昵称" >
          <template slot-scope="scope">
             <div> {{ selection[0].nickname }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="headImg" label="头像" >
          <template slot-scope="scope">
            <img :src="selection[0].headImgUrl" style="width: 50px;height: 50px;border-radius: 50px" />
          </template>
        </el-table-column>
        <el-table-column prop="videoDisc" label="视频描述" >
          <template slot-scope="scope">
            <div>{{ scope.row.desc.description }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="操作时间">
          <template slot-scope="scope">
            <div>{{ relativeTime(scope.row.createTime) }}</div>
          </template>
        </el-table-column>



        <el-table-column prop="loginDate" label="登录时间" ></el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitLowerForm">确 定</el-button>
        <el-button @click="cancelLower">取 消</el-button>
      </div>
    </el-dialog>



  </div>
</template>

<script>
import { listMediaAccount,   delMediaAccount, addAccount, updateMediaAccount,getMediaAccount,bindLowerUser } from "@/api/media/mediaAccount";
import { listPlatform } from "@/api/media/platform";
import { ChromeService, ChromeChannel, MAIN } from '@/utils/chrome_plug'
import { listAccountGroupData,addAccountGroup,delAccountGroup,updateAccountGroup } from "@/api/media/accountGroup";
import { Message } from "element-ui";
import groupSelect from '@/views/media/accountGroup/groupSelect/index'
import {ipcApiRoute} from "@/api/main";
import Vue from 'vue'
import { getLowerUser, createLowerUser,updateLowerUserData,delUser } from "@/api/system/user";
export default {
  name: "Account",
  components:{
    groupSelect
  },
  data() {
    return {
      userId: '',
      templateRadio:'',
      specialList:[],
      draftsList:[],
      loadSpecial:false,
      specialOpen:false,
      loadLowerUser:false,
      lowerOpen:false,
      lowerUserList:{},
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      selection:{},
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 账号管理表格数据
      accountList: [],
      accUser:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //平台配置列表
      platformList:[],
      restaurants:[],
      state: '',
      groupData:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
        userId: undefined,
        platform: undefined,
        logo: undefined,
        nickname: undefined,
        headImgUrl: undefined,
        cookies: undefined,
        loginStatus: undefined,
        groupName:undefined,
        lastScanTime: undefined,
        acctType: undefined,
        scanRandom: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getGroup();
    this.getListPlatform();

  },
  methods: {


    /**
     * 复制链接
     * @param data
     */
    copyLink(data){
      let url = data;
      let oInput = document.createElement('input');
      oInput.value = url;
      document.body.appendChild(oInput);
      oInput.select(); // 选择对象;
      document.execCommand("Copy");
      Message.success("复制成功！")
      oInput.remove()
    },


    /**
     * @param {Object} pastTimestamp
     * 获取时间显示
     */
    relativeTime(pastTimestamp) {
      const currentTime = Math.floor(Date.now() / 1000); // Current time in seconds
      const secondsAgo = currentTime - pastTimestamp;

      // Convert seconds to appropriate relative time
      if (secondsAgo < 60) {
        return '刚刚';
      } else if (secondsAgo < 3600) {
        return `${Math.floor(secondsAgo / 60)}分钟前`;
      } else if (secondsAgo < 86400) {  // It will be true for anything less than 24 hours
        return `${Math.floor(secondsAgo / 3600)}小时前`;
      } else {
        return `${Math.ceil(secondsAgo / 86400)}天前`;  // Use Math.ceil to round up
      }
    },

    /** 获取下级用户数据 */
    getLowerUserList() {
      this.loadLowerUser = true;
      getLowerUser({}).then(response => {
        console.log(response.data)
        this.lowerUserList = response.data
      }).finally(()=>{
        this.loadLowerUser = false;
      })
    },


    /**
     * 修改账号特效
     */
    updateSpecial(){
      console.log(this.selection)
      this.specialOpen = true ;
      this.getDrafts();
    },


    /**
     * 获取草稿箱列表
     */
    async getDrafts(){
      let arg = {
        cookies:this.selection[0].cookies,
        _log_finder_id:this.selection[0].finderUserName
      }
      let data = await this.serviceInvoke("controller.media.getDraftsList",arg);
      let dataSource = JSON.parse(data);
      console.log(dataSource.data.list)
      this.draftsList = dataSource.data.list.sort((a, b) => b.createTime - a.createTime);
    },



    /**
     * 单选表格
     */
    singleElection(row){
      this.userId = this.lowerUserList.indexOf(row);
    },

    /**
     * 分配账号给指定用户
     */
    submitLowerForm(){
      let bandUserData = {
        idList: this.ids,
        lowerUserId:this.userId
      }
      bindLowerUser(bandUserData).then((res)=>{
        Message.success("绑定成功！")
        this.cancelLower();
      }).finally(()=>{
        this.getList();
      })
    },

    /**
     * 取消
     */
    cancelLower(){
      this.lowerOpen = false;
    },


    /**
     * 获取平台配置
     */
    getListPlatform(){
      listPlatform({status : 1}).then(res=>{
        console.log(res)
        if(res.code === 200){
          this.platformList = res.rows
        }else{
          Message.error("平台列表查询失败！");
        }
      })
    },


    /**
     * 将账号分配给下级用户
     */
    setLowerUser(){
      this.lowerOpen = true;
      this.getLowerUserList();
    },

    /**
     * 加载分组数据
     */
    getGroup(){
      listAccountGroupData({pageNum: 1,pageSize: 50}).then((res)=>{
        let data =  res.rows;
        for(var i = 0 ; i < data.length;i++){
          let item =  Object.assign({},data[i],{value:data[i].groupTitle})
          this.groupData.push(item)
        }
        this.restaurants = this.groupData
      })
    },


    /**
     * 获取查询参数
     * @param queryString
     * @param callback
     */
    querySearch(queryString, callback) {
      callback(this.restaurants)
    },

    /**
     * 查询
     */
    handleSelect(){
      console.log(this.form.groupTitle)
      // console.log(searchData)
      // let data = []
      //   this.groupData.forEach((item)=>{
      //     if(item.indexOf(searchData) !== -1){
      //       data.push(item)
      //     }
      //   })
      // this.restaurants = data
      // this.querySearch();
    },



    /**
     * 获取分组数据
     * @param item
     */
    getGroupData(item){
      console.log(item)
      this.queryParams.groupId = item.id
      this.getList()
    },


    /**
     * 获取对应平台的链接
     */
    getPlatformUrl(row){
      return new Promise((resolve)=>{
        this.platformList.forEach((item)=>{
          if(row.platformCode === item.platformCode){
            resolve(item.url)
          }
        })
      })
    },


    /**
     * 视频号账号跳转页面
     * @param findurl
     * @returns {Promise<void>}
     */
    async  loginWeb(row) {
      if(!this.$isweb){
        Message.error("如需登录后台页面，请使用网页端！")
        return;
      }
      if(row.loginStatus === 0){
        Message.error("账号已掉线！")
        return;
      }
      //获取对应平台的链接
      let link  = await this.getPlatformUrl(row);
      await this.SendMessage({
        func: ChromeService.REMOVE_COOKIE,
        args: { url: link },
        js: MAIN
      })
      await this.SendMessage({
        func: ChromeService.SET_COOKIE,
        args: { url: link, cookie: JSON.parse(row.cookies) },
        js: MAIN
      })
      await this.SendMessage({
        func: ChromeChannel.CHANNELS.GETSETFINDWE,
        args: {data:row} ,
        js: MAIN
      })
      window.open(link)
    },


    /**
     * 发送插件消息
     * @param object
     * @returns {Promise<unknown>}
     * @constructor
     */
    SendMessage(object) {
      return new Promise((resolve, reject) => {
        try {
          chrome.runtime.sendMessage(Vue.prototype.ChromeId, object, response => {
            resolve(response)
          })
        } catch (error) {
          reject(error)
        }
      })
    },


    /** 查询账号管理列表 */
    getList() {
      this.loading = true;
      listMediaAccount(this.queryParams).then(response => {
        this.accountList = response.rows;
        this.total = response.total;
      }).finally(()=>{
        this.loading = false;
      })
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        pageNum: 1,
        pageSize: 10,
        id: undefined,
        deptId: undefined,
        userId: undefined,
        platform: undefined,
        logo: undefined,
        groupName:undefined,
        nickname: undefined,
        headImgUrl: undefined,
        cookies: undefined,
        loginStatus: undefined,
        lastScanTime: undefined,
        acctType: undefined,
        scanRandom: undefined,
        idList:undefined,
        // remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      }
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection;
      this.accUser.push(selection)
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加账号管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.loading = true;
      this.open = true;
      // this.reset();
      // const id = row.id || this.ids
      // getMediaAccount(id).then(response => {
      //   console.log(response)
      //   this.loading = false;
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改账号管理";
      // });
      // this.loading = false;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.ids.length > 0) {
            this.form.idList = this.ids
            updateMediaAccount(this.form).then(response => {
              console.log(response)
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            Message.error("错误！")
          }
          // else {
          //   addAccount(this.form).then(response => {
          //     this.$modal.msgSuccess("新增成功");
          //     this.open = false;
          //     this.getList();
          //   }).finally(() => {
          //     this.buttonLoading = false;
          //   });
          // }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除账号管理编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delMediaAccount(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport(row) {
      // const ids = row.id || this.ids;
      // let idStr = ''
      // if(ids){
      //   for(let i = 0 ; i < ids.length;i++){
      //     idStr += ids[i] + ','
      //   }
      //   this.queryParams.ids = idStr
      // }
      this.download('media/mediaAccount/export', {
        ...this.queryParams
      }, `account_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
